package com.fl.nj.controller;

import com.fl.nj.entity.ServerService;
import com.fl.nj.service.ServerServiceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 服务Controller
 * 提供RESTful API接口，用于管理服务器上的服务
 */
@RestController
@RequestMapping("/api/server-services")
public class ServerServiceController {
    
    @Autowired
    private ServerServiceService serverServiceService;
    
    /**
     * 获取所有服务信息（包含服务类型和设备名称）
     * @return 服务列表
     */
    @GetMapping
    public ResponseEntity<List<ServerService>> getAllServerServices() {
        List<ServerService> services = serverServiceService.getAllWithDetails();
        return ResponseEntity.ok(services);
    }
    
    /**
     * 分页查询服务信息
     * @param page 页码
     * @param pageSize 每页条数
     * @param serviceName 服务名称关键词（可选）
     * @param serviceTypeId 服务类型ID（可选）
     * @param deviceId 设备ID（可选）
     * @param status 服务状态（可选）
     * @return 服务列表及分页信息
     */
    @GetMapping("/page")
    public ResponseEntity<Map<String, Object>> getServerServicesByPage(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String serviceName,
            @RequestParam(required = false) Long serviceTypeId,
            @RequestParam(required = false) Long deviceId,
            @RequestParam(required = false) String status) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("page", page);
            params.put("pageSize", pageSize);
            params.put("serviceName", serviceName);
            params.put("serviceTypeId", serviceTypeId);
            params.put("deviceId", deviceId);
            params.put("status", status);
            
            List<ServerService> services = serverServiceService.getPageListWithDetails(params);
            int total = serverServiceService.getTotal(params);
            
            result.put("success", true);
            result.put("data", services);
            result.put("total", total);
            result.put("page", page);
            result.put("pageSize", pageSize);
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取服务列表失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
    
    /**
     * 根据ID获取服务信息
     * @param id 服务ID
     * @return 服务信息
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getServerServiceById(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            ServerService service = serverServiceService.getById(id);
            if (service == null) {
                result.put("success", false);
                result.put("message", "服务不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
            result.put("success", true);
            result.put("data", service);
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取服务信息失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
    
    /**
     * 根据设备ID获取服务列表
     * @param deviceId 设备ID
     * @return 服务列表
     */
    @GetMapping("/device/{deviceId}")
    public ResponseEntity<List<ServerService>> getServerServicesByDeviceId(@PathVariable Long deviceId) {
        List<ServerService> services = serverServiceService.getByDeviceId(deviceId);
        return ResponseEntity.ok(services);
    }
    
    /**
     * 测试端点：比较getPageListWithDetails和getTotal方法的结果，用于调试计数不一致问题
     * @return 包含两个计数结果的Map
     */
    @GetMapping("/test-count")
    public ResponseEntity<Map<String, Object>> getTestServiceCount() {
        try {
            Map<String, Object> result = new HashMap<>();
            
            // 使用空参数Map来调用两个方法
            Map<String, Object> params = new HashMap<>();
            params.put("page", 1);
            params.put("pageSize", 10);
            params.put("start", 0);
            
            // 调用getPageListWithDetails并获取结果数量
            List<ServerService> services = serverServiceService.getPageListWithDetails(params);
            int listSize = services != null ? services.size() : 0;
            
            // 调用getTotal获取总数
            int totalCount = serverServiceService.getTotal(params);
            
            // 将两个结果都放入返回Map中
            result.put("listSize", listSize);
            result.put("totalCount", totalCount);
            result.put("timestamp", System.currentTimeMillis());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("error", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
        }
    }
    
    /**
     * 创建服务
     * @param serverService 服务信息
     * @return 创建结果
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> createServerService(@RequestBody ServerService serverService) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 验证参数
            if (serverService.getServiceName() == null || serverService.getServiceName().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "服务名称不能为空");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
            }
            if (serverService.getServiceTypeId() == null) {
                result.put("success", false);
                result.put("message", "服务类型不能为空");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
            }
            if (serverService.getDeviceId() == null) {
                result.put("success", false);
                result.put("message", "所属设备不能为空");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
            }
            if (serverService.getStatus() == null || serverService.getStatus().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "服务状态不能为空");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
            }
            
            boolean success = serverServiceService.save(serverService);
            if (success) {
                result.put("success", true);
                result.put("message", "服务创建成功");
                result.put("data", serverService);
                return ResponseEntity.status(HttpStatus.CREATED).body(result);
            } else {
                result.put("success", false);
                result.put("message", "该设备下已存在同名服务");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
            }
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "创建服务失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
    
    /**
     * 更新服务
     * @param id 服务ID
     * @param serverService 服务信息
     * @return 更新结果
     */
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updateServerService(@PathVariable Long id, @RequestBody ServerService serverService) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 验证参数
            if (serverService.getServiceName() == null || serverService.getServiceName().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "服务名称不能为空");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
            }
            if (serverService.getServiceTypeId() == null) {
                result.put("success", false);
                result.put("message", "服务类型不能为空");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
            }
            if (serverService.getDeviceId() == null) {
                result.put("success", false);
                result.put("message", "所属设备不能为空");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
            }
            if (serverService.getStatus() == null || serverService.getStatus().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "服务状态不能为空");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
            }
            
            serverService.setId(id);
            boolean success = serverServiceService.update(serverService);
            if (success) {
                result.put("success", true);
                result.put("message", "服务更新成功");
                result.put("data", serverService);
                return ResponseEntity.ok(result);
            } else {
                // 检查是因为不存在还是名称重复
                ServerService existing = serverServiceService.getById(id);
                if (existing == null) {
                    result.put("success", false);
                    result.put("message", "服务不存在");
                    return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
                } else {
                    result.put("success", false);
                    result.put("message", "该设备下已存在同名服务");
                    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
                }
            }
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新服务失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
    
    /**
     * 删除服务
     * @param id 服务ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteServerService(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = serverServiceService.delete(id);
            if (success) {
                result.put("success", true);
                result.put("message", "服务删除成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "服务不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除服务失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
}